Genetic Algorithm Example

This is a simple example of Genetic Algorithms using Python and the deap library.

Genetic Algorithm Overview

Genetic Algorithms are optimization algorithms inspired by the process of natural selection. They operate by evolving a population of candidate solutions over multiple generations. Each solution, often represented as a chromosome, undergoes genetic operations such as selection, crossover, and mutation to produce new candidate solutions. The goal is to find an optimal or near-optimal solution to a given problem.

Key concepts of Genetic Algorithms:

Python Source Code:

# Import necessary libraries
import random
from deap import base, creator, tools

# Define the optimization problem
creator.create("FitnessMin", base.Fitness, weights=(-1.0,))
creator.create("Individual", list, fitness=creator.FitnessMin)

# Define the genetic operators
toolbox = base.Toolbox()
toolbox.register("attr_float", random.uniform, -5.0, 5.0)
toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_float, n=5)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)

def evaluate(individual):
    # Example objective function: minimize the sum of squares
    return sum(x**2 for x in individual),

toolbox.register("evaluate", evaluate)
toolbox.register("mate", tools.cxBlend, alpha=0.5)
toolbox.register("mutate", tools.mutGaussian, mu=0, sigma=1, indpb=0.2)
toolbox.register("select", tools.selTournament, tournsize=3)

# Create an initial population
population = toolbox.population(n=10)

# Run the Genetic Algorithm
ngen = 50
for gen in range(ngen):
    offspring = algorithms.varAnd(population, toolbox, cxpb=0.7, mutpb=0.2)
    fits = toolbox.map(toolbox.evaluate, offspring)
    for fit, ind in zip(fits, offspring):
        ind.fitness.values = fit
    population = toolbox.select(offspring, k=len(population))

# Print the final population
print("Final Population:")
for ind in population:
    print(ind, ind.fitness.values)

Explanation: